/** K线数据更新 **/

export default function KlineUpdate(KlineView) {
  // 获取 市场行情 历史K线
  const reqKlineHistoryData = async function(recvData) {
    var klineArray = []
    var length = recvData.data.length
    for (var i = 0; i < length; i++) {
      var item = recvData.data[i]

      var timestamp = new Date()
      timestamp.setTime(item.id * 1000)
      timestamp = timestamp.getTime()
      var kLineModel = {
        open: item.open,
        low: item.low,
        high: item.high,
        close: item.close,
        volume: item.vol, // 成交量 vol（成交合约张数） 相当于 amount（成交币）
        timestamp: String(timestamp), // vite 不兼容 klinecharts.js
        turnover: item.trade_turnover // 成交额
      }
      klineArray.push(kLineModel)
    }

    KlineView.kLineChart.value.applyNewData(klineArray) // 设置数据
  }

  // 订阅最新 市场行情 （最新成交）
  const subKlineNewestData = async function(recvData) {
    if (recvData.id) {
      var item = recvData
      var timestamp = new Date()
      timestamp.setTime(item.id * 1000)
      timestamp = timestamp.getTime()
      const dataList = KlineView.kLineChart.value.getDataList() // 获取数据
      const length = dataList.length
      if (length) {
        const kLineModel = Object.assign({}, dataList[length - 1]) // 浅拷贝
        kLineModel.open = item.open
        kLineModel.low = item.low
        kLineModel.high = item.high
        kLineModel.close = item.close
        kLineModel.volume = item.volume
        kLineModel.timestamp = String(timestamp) // vite 不兼容 klinecharts.js
        kLineModel.turnover = item.trade_turnover

        KlineView.kLineChart.value.updateData(kLineModel)
      }
    }
  }

  return {
    reqKlineHistoryData,
    subKlineNewestData
  }
}
